from torch import nn
import math
import torch.utils.model_zoo as model_zoo
import torch
import torch.nn.functional as F
from copy import deepcopy
from other_layers import *
from functools import partial
from GCN import GCN


__all__ = ['ResNet',  'resnet34', 'resnet50', 'resnet101',
            'resnet50_cat',
           'resnet50_cat_dilate']

model_urls = {
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}


def conv3x3(in_planes, out_planes, stride=1):
    "3x3 convolution with padding"
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)


class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
                               padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm2d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class ResNet(nn.Module):

    def __init__(self, block, layers, num_classes=1000):
        self.inplanes = 64
        super(ResNet, self).__init__()
        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)  # 1/16
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)  # 1/32
        self.avgpool = nn.AdaptiveAvgPool2d(output_size=1)
        self.fc = nn.Linear(512 * block.expansion, num_classes)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)

        x = self.layer3(x)

        x = self.layer4(x)

        x = self.avgpool(x)

        x = x.view(x.size(0), -1)
        x = self.fc(x)
        return x
def initialize_weights(*models):
    for model in models:
        for module in model.modules():
            if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):
                nn.init.kaiming_normal(module.weight)
                if module.bias is not None:
                    module.bias.data.zero_()
            elif isinstance(module, nn.BatchNorm2d):
                module.weight.data.fill_(1)
                module.bias.data.zero_()

# many are borrowed from https://github.com/ycszen/pytorch-ss/blob/master/gcn.py
class _GlobalConvModule(nn.Module):
    def __init__(self, in_dim, out_dim, kernel_size):
        super(_GlobalConvModule, self).__init__()
        pad0 = (kernel_size[0] - 1) / 2
        pad1 = (kernel_size[1] - 1) / 2
        # kernel size had better be odd number so as to avoid alignment error
        super(_GlobalConvModule, self).__init__()
        self.conv_l1 = nn.Conv2d(in_dim, out_dim, kernel_size=(kernel_size[0], 1),
                                 padding=(pad0, 0))
        self.conv_l2 = nn.Conv2d(out_dim, out_dim, kernel_size=(1, kernel_size[1]),
                                 padding=(0, pad1))
        self.conv_r1 = nn.Conv2d(in_dim, out_dim, kernel_size=(1, kernel_size[1]),
                                 padding=(0, pad1))
        self.conv_r2 = nn.Conv2d(out_dim, out_dim, kernel_size=(kernel_size[0], 1),
                                 padding=(pad0, 0))

    def forward(self, x):
        x_l = self.conv_l1(x)
        x_l = self.conv_l2(x_l)
        x_r = self.conv_r1(x)
        x_r = self.conv_r2(x_r)
        x = x_l + x_r
        return x


class _BoundaryRefineModule(nn.Module):
    def __init__(self, dim):
        super(_BoundaryRefineModule, self).__init__()
        self.relu = nn.ReLU(inplace=True)
        self.conv1 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)
        self.conv2 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)

    def forward(self, x):
        residual = self.conv1(x)
        residual = self.relu(residual)
        residual = self.conv2(residual)
        out = x + residual
        return out



class FSLM_ResGCN(nn.Module):
    def __init__(self, FSnum_classes, LMnum_classes, input_size):
        super(FSLM_ResGCN, self).__init__()
        pretrained_model = resnet50(pretrained=True)
        self.input_size = input_size

        self.conv1 = pretrained_model.conv1 # 1/2
        self.bn1 = pretrained_model.bn1
        self.relu = pretrained_model.relu
        self.maxpool = pretrained_model.maxpool  # 1/4
        self.layer1 = pretrained_model.layer1  # 1/4
        self.layer2 = pretrained_model.layer2  # 1/8
        self.layer3 = pretrained_model.layer3  # 1/16
        self.layer4 = pretrained_model.layer4  # 1/32
        self.avgpool = nn.AdaptiveAvgPool2d(1)
        self.fc = cat_linear(in_features=2048, out_features_list=FSnum_classes)

        self.layer3.apply(partial(_nostride_dilate, dilate=2))
        self.layer4.apply(partial(_nostride_dilate, dilate=4))


        # GCN part
        self.gcm1 = _GlobalConvModule(2048, LMnum_classes, (7, 7))
        self.gcm2 = _GlobalConvModule(1024, LMnum_classes, (7, 7))
        self.gcm3 = _GlobalConvModule(512, LMnum_classes, (7, 7))
        self.gcm4 = _GlobalConvModule(256, LMnum_classes, (7, 7))

        self.brm1 = _BoundaryRefineModule(LMnum_classes)
        self.brm2 = _BoundaryRefineModule(LMnum_classes)
        self.brm3 = _BoundaryRefineModule(LMnum_classes)
        self.brm4 = _BoundaryRefineModule(LMnum_classes)
        self.brm5 = _BoundaryRefineModule(LMnum_classes)
        self.brm6 = _BoundaryRefineModule(LMnum_classes)
        self.brm7 = _BoundaryRefineModule(LMnum_classes)
        self.brm8 = _BoundaryRefineModule(LMnum_classes)
        self.brm9 = _BoundaryRefineModule(LMnum_classes)

        initialize_weights(self.gcm1, self.gcm2, self.gcm3, self.gcm4, self.brm1, self.brm2, self.brm3,
                           self.brm4, self.brm5, self.brm6, self.brm7, self.brm8, self.brm9)

    def forward(self, x, isClf=True):
        # clf task
        if isClf:
            x = self.conv1(x)
            x = self.bn1(x)
            x = self.relu(x)
            x = self.maxpool(x)

            x = self.layer1(x)
            x = self.layer2(x)
            x = self.layer3(x)
            x = self.layer4(x)

            x = self.avgpool(x)

            x = x.view(x.size(0), -1)
            x = self.fc(x)
            return x

        # seg task
        else:
            x = self.conv1(x)
            x = self.bn1(x)
            fm0 = self.relu(x)

            fm1 = self.maxpool(fm0)  # 256
            fm1 = self.layer1(fm1)  # 128
            fm2 = self.layer2(fm1)  # 64
            fm3 = self.layer3(fm2)  # 32
            fm4 = self.layer4(fm3)  # 16

            gcfm1 = self.brm1(self.gcm1(fm4))  # 16
            gcfm2 = self.brm2(self.gcm2(fm3))  # 32
            gcfm3 = self.brm3(self.gcm3(fm2))  # 64
            gcfm4 = self.brm4(self.gcm4(fm1))  # 128

            fs1 = self.brm5(F.upsample(gcfm1, fm3.size()[2:], mode='bilinear') + gcfm2)  # 32
            fs2 = self.brm6(F.upsample(fs1, fm2.size()[2:], mode='bilinear') + gcfm3)  # 64
            fs3 = self.brm7(F.upsample(fs2, fm1.size()[2:], mode='bilinear') + gcfm4)  # 128
            fs4 = self.brm8(F.upsample(fs3, fm0.size()[2:], mode='bilinear'))  # 256
            out = self.brm9(F.upsample(fs4, self.input_size, mode='bilinear'))  # 512
            return out





def resnet34(pretrained=False, **kwargs):
    """Constructs a ResNet-34 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))
    return model


def resnet50(pretrained=False, **kwargs):
    """Constructs a ResNet-50 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
    return model


def resnet50_cat_dilate( num_classes, pretrained=True):
    base_model = resnet50(pretrained=pretrained)
    base_model.fc = cat_linear(2048, num_classes)
    base_model.layer3.apply(partial(_nostride_dilate, dilate=2))
    base_model.layer4.apply(partial(_nostride_dilate, dilate=4))
    return base_model


def _nostride_dilate( m, dilate):
    classname = m.__class__.__name__
    if classname=='Conv2d':
        # the convolution with stride
        if m.stride == (2, 2):
            m.stride = (1, 1)
            if m.kernel_size == (3, 3):
                m.dilation = (dilate//2, dilate//2)
                m.padding = (dilate//2, dilate//2)
        # other convoluions
        else:
            if m.kernel_size == (3, 3):
                m.dilation = (dilate, dilate)
                m.padding = (dilate, dilate)

if __name__ == '__main__':
    model = FSLM_ResGCN(FSnum_classes=[5,10], LMnum_classes=24, input_size=(336,336))
    # print model
    x = torch.FloatTensor(10,3,336,336)
    x = torch.autograd.Variable(x)
    y = model(x, isClf=False)
    print y.size()